package core;

import branch.Branch;
import gitobject.Commit;
import gitobject.Tree;
import repository.Repository;
import stage.Index;
import stage.IndexElement;

import java.io.*;
import java.util.*;

public class JitCommit {
    private static String path = Repository.getGitDir();

    /**
     * create commit and write it into repository
     * @throws Exception
     */
    public void commit(String commitMessage) throws Exception {
        Tree tree = buildIndexTree();
        String author;
        String committer;
        String message = commitMessage;
        String userName = "";
        String userEmail = "";

        if (new File(path + File.separator + "config").exists()) {  //"C:\\Users\\Adrian\\.gitconfig"
            File info = new File(path + File.separator + "config"); //"C:\\Users\\Adrian\\.gitconfig"
            FileInputStream is = new FileInputStream(info);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            try {
                String line = br.readLine();
                while (line != null) {
                    if (line.contains("name")) {
                        String[] tmp = line.split(" ");
                        userName = tmp[2];
                    }
                    if (line.contains("email")) {
                        String[] tmp1 = line.split(" ");
                        userEmail = tmp1[2];
                    }
                    line = br.readLine();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new IOException("Index file doesn't exist.");
        }
        author = userName + " " + userEmail + " " + String.valueOf(new Date().getTime()) + " " + "+0800";
        committer = userName + " " + userEmail + " " + String.valueOf(new Date().getTime()) + " " + "+0800";

        Commit commit = new Commit(tree, author, committer, message);
        updateBranch(commit);
        branch.Branch curBranch = JitBranch.getCurBranch();
        System.out.println("[" + curBranch.branchName + "\s" + commit.getKey().substring(0,7) + "]"
                + "\s" + message + "\n");
    }

    /**
     * build IndexTree
     * @return Tree tree
     * @throws Exception
     */
    public Tree buildIndexTree() throws Exception {
        HashMap<String, IndexElement> root = new HashMap<>();
        LinkedList<String[]> idxList = Index.getInstance().indexFileList;

        for (String[] record : idxList) {
            String dirName = record[2];
            List<String> segPath = Arrays.asList(dirName.split("\\\\"));

            HashMap<String, IndexElement> cur = root;
            for (int i = 0; i < segPath.size() - 1; i++) {    //diretion
                String str = segPath.get(i);
                if (cur.containsKey(str)) {
                    cur = cur.get(str).indexTree;
                } else {
                    HashMap<String, IndexElement> t = new HashMap<>();
                    cur.put(str, new IndexElement(str, "", t));
                    cur = t;
                }
            }
            String fileName = segPath.get(segPath.size() - 1);    //is file
            cur.put(fileName, new IndexElement(fileName, record[1]));    //insert a file
        }

        Tree tree = new Tree(root);  //overload Tree()
        return tree;
    }

    /**
     * update branch info after a new commit object is created
     * @param commit
     * @throws IOException
     */
    public void updateBranch(Commit commit) throws IOException {
        String commitId = commit.getKey();
        String path = Repository.getGitDir() + File.separator + "refs" + File.separator + "heads";
        //System.out.println(path);
        File file = new File(path);
        if(file.list().length == 0) {	//master branch hasn't been created.
            branch.Branch master = new branch.Branch("master", commitId);
        }
        Branch b = JitBranch.getCurBranch();
        b.commitID = commitId;
    }
}


